#import "MainScene.h"
#import "CoreDataStack.h"
#import "Player.h"

@implementation MainScene {
    CCLabelTTF *_textLabel;
    CCTextField *_textField;
    
    NSManagedObjectContext *_context;
    NSMutableArray *_dataArray;
}

- (void)didLoadFromCCB {
    NSLog(@"加载了MainScene");
    CoreDataStack *defaultCoreDataStack = [CoreDataStack sharedCoreDataStack];
    NSLog(@"defaultCoreDataStack:%@",defaultCoreDataStack);
    _context = defaultCoreDataStack.context;
    
    [self updateUI];
//    _dataArray = [NSMutableArray array];
//    NSLog(@"returnString:%@",[self stringWithArray:_dataArray]);

}

- (void)add {
    if ([_textField.string isEqualToString:@""]) {
        return;
    }
    Player *player = [NSEntityDescription insertNewObjectForEntityForName:@"Player" inManagedObjectContext:_context];
    player.name = _textField.string;
    NSError *error;
    [_context save:&error];
    
//    [_dataArray addObject:_textField.string];
    [self updateUI];
}
#pragma mark -
- (void)updateUI {
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Player"];
    NSError *error;
    NSArray *playerArray = [_context executeFetchRequest:request error:&error];
    if (playerArray == nil) {
        //        _peopleArray = [NSMutableArray array];
        NSLog(@"error");
    }
    
    _dataArray = [NSMutableArray arrayWithArray:playerArray];
    for (Player *player in _dataArray) {
        NSString *name = player.name;
        NSLog(@"creat,name:%@",name);
    }

    
    _textLabel.string = [self stringWithArray:_dataArray];
}

- (NSString *)stringWithArray:(NSMutableArray *)array {
    if (array.count == 0) {
        return @"";
    } else {
        Player *firstPlayer = array.firstObject;
        NSString *returnString = firstPlayer.name;
        
        for (NSUInteger i = 1; i < array.count; i++) {
            Player *aPlayer = array[i];
            NSString *aString = aPlayer.name;
            returnString = [NSString stringWithFormat:@"%@\n%@",returnString,aString];
        }
        return returnString;
    }
}
@end
